package com.ctsi.security.event.organ;

import com.ctsi.commons.event.AbstractObserver;
import com.ctsi.commons.event.BaseEvent;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.SRoleUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class InsertUserLoginHandler extends AbstractObserver {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4347305912686430850L;
	private static Logger logger = LoggerFactory.getLogger(InsertUserLoginHandler.class);
	public static final String ORDINARYPERSON="security_ordinary";
	private static PermissionRole sroleService;
	private static PersonServiceProxy personService = OrganiseFactoryBean.getInstance().getPersonServiceProxy();

	public static void setSroleService(PermissionRole sroleService) {
		InsertUserLoginHandler.sroleService = sroleService;
	}

	/**
     * 
     */
    private static PersonServiceProxy getPersonService(){
    	return personService;
    }
    
	@Override
	public void onEvent(Object[] args) {
		BaseEvent event= (BaseEvent) args[0];
		UserLogin userLogin=(UserLogin) event.getSource();
		//判断是否是外部用户
//		if(userLogin.getPartyId().startsWith(UserLoginServiceProxy.outerPerson)){
//			return;
//		}

		//在普通人员角色中增加
	//	getSRoleService().saveAllRoleUser(ORDINARYPERSON,new String[]{userLogin.getLoginId()}, new String[]{personName}, new String[]{userLogin.getPartyId()});
		//查找到该人员所具有的组织
		List<Organise> organList=getPersonService().getBelongOrgan(userLogin.getPartyId());
		Person person = personService.findPersonById(userLogin.getPartyId());
		if(UtilValidate.isNotEmpty(organList)){
			for(Organise organItem : organList){
				List<String> roleList=sroleService.getRoleIdsByPartyId(organItem.getPartyId());
				for(String roleId : roleList){
					SRoleUser sroleUser=new SRoleUser();
					sroleService.setJoinWay(SRoleUser.joinWayAuto,sroleUser);
					sroleUser.setLoginId(userLogin.getId());
					sroleUser.setLoginName(person.getFullName());
					sroleUser.setParentId(organItem.getPartyId());
					sroleUser.setPartyId(userLogin.getPartyId());
					sroleUser.setRefCount(1);
					sroleUser.setRoleId(roleId);
					sroleService.addRoleUser(roleId, sroleUser, SRoleUser.joinWayAuto);
				}
			}
	
		}
		logger.info("{} has been added",userLogin.getId());
	}
}
